home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 24 / CU Amiga Magazine's Super CD-ROM 24 (1998)(EMAP Images)(GB)(Track 1 of 2)[!][issue 1998-07].iso / CUCD / Programming / SWI / source / man / module.doc (.txt) < prev    next >
Encoding:
LaTeX Document  |  1997-07-02  |  21.9 KB  |  446 lines

  1. \chapter{Using Modules}                 \label{sec:modules}
  2. \section{Why Using Modules?}
  3. In traditional Prolog systems the predicate space was flat.  This
  4. approach is not very suitable for the development of large
  5. applications, certainly not if these applications are developed by
  6. more than one programmer.  In many cases, the definition of a Prolog
  7. predicate requires sub-predicates that are intended only to complete
  8. the definition of the main predicate.  With a flat and global
  9. predicate space these support predicates will be visible from the
  10. entire program.
  11. For this reason, it is desirable that each source module has it's own
  12. predicate space.  A module consists of a declaration for it's name,
  13. it's \jargon{public predicates} and the predicates themselves.  This
  14. approach allow the programmer to use short (local) names for support
  15. predicates without worrying about name conflicts with the support
  16. predicates of other modules.  The module declaration also makes
  17. explicit which predicates are meant for public usage and which for
  18. private purposes.  Finally, using the module information, cross
  19. reference programs can indicate possible problems much better.
  20. \section{Name-based versus Predicate-based Modules}
  21. Two approaches to realize a module system are commonly used in Prolog
  22. and other languages. The first one is the \jargon{name based} module
  23. system. In these systems, each atom read is tagged (normally prefixed)
  24. with the module name, with the exception of those atoms that are defined
  25. \jargon{public}. In the second approach, each module actually implements
  26. its own predicate space.
  27. A critical problem with using modules in Prolog is introduced by the
  28. meta-predicates that transform between Prolog data and Prolog
  29. predicates.  Consider the case where we write:
  30. \begin{code}
  31. :- module(extend, [add_extension/3]).
  32. add_extension(Extension, Plain, Extended) :-
  33.         maplist(extend_atom(Extension), Plain, Extended).
  34. extend_atom(Extension, Plain, Extended) :-
  35.         concat(Plain, Extension, Extended).
  36. \end{code}
  37. In this case we would like maplist to call {extend_atom}/3 in the module
  38. \const{extend}.  A name based module system will do this correctly. It
  39. will tag the atom \const{extend_atom} with the module and maplist will
  40. use this to construct the tagged term {extend_atom}/3.  A name based
  41. module however, will not only tag the atoms that will eventually be
  42. used to refer to a predicate, but \strong{all} atoms that are not declared
  43. public.  So, with a name based module system also data is local to the
  44. module.  This introduces another serious problem:
  45. \begin{code}
  46. :- module(action, [action/3]).
  47. action(Object, sleep, Arg) :- ....
  48. action(Object, awake, Arg) :- ....
  49. :- module(process, [awake_process/2]).
  50. awake_process(Process, Arg) :-
  51.         action(Process, awake, Arg).
  52. \end{code}
  53. This code uses a simple object-oriented implementation technique
  54. were atoms are used as method selectors.  Using a name based module
  55. system, this code will not work, unless we declare the selectors
  56. public atoms in all modules that use them.  Predicate based module
  57. systems do not require particular precautions for handling this case.
  58. It appears we have to choose either to have local data, or to have
  59. trouble with meta-predicates.  Probably it is best to choose for
  60. the predicate based approach as novice users will not often write
  61. generic meta-predicates that have to be used across multiple modules,
  62. but are likely to write programs that pass data around across
  63. modules.  Experienced Prolog programmers should be able to deal with 
  64. the complexities of meta-predicates in a predicate based module
  65. system.
  66. \section{Defining a Module}
  67. Modules normally are created by loading a \jargon{module file}.  A module
  68. file is a file holding a module/2 directive as its first term.  The
  69. module/2 directive declares the name and the public (i.e.\
  70. externally visible) predicates of the module.  The rest of the file
  71. is loaded into the module.  Below is an example of a module file,
  72. defining reverse/2. 
  73. \begin{code}
  74. :- module(reverse, [reverse/2]).
  75. reverse(List1, List2) :-
  76.         rev(List1, [], List2).
  77. rev([], List, List).
  78. rev([Head|List1], List2, List3) :-
  79.         rev(List1, [Head|List2], List3).
  80. \end{code}
  81. \section{Importing Predicates into a Module}
  82. As explained before, in the predicate based approach adapted by
  83. SWI-Prolog, each module has it's own predicate space.  In SWI-Prolog,
  84. a module initially is completely empty.  Predicates can be added
  85. to a module by loading a module file as demonstrated in the previous
  86. section, using assert or by \jargon{importing} them from another module.
  87. Two mechanisms for importing predicates explicitly from another module
  88. exist.  The use_module/[1,2] predicates load a module file and import
  89. (part of the) public predicates of the file.  The import/1 predicate
  90. imports any predicate from any module.
  91. \begin{description}
  92. \predicate{use_module}{1}{+File}
  93. Load the file(s) specified with \arg{File} just like ensure_loaded/1.
  94. The files should all be module files.  All exported predicates from the
  95. loaded files are imported into the context module.  The difference
  96. between this predicate and ensure_loaded/1 becomes apparent if the file
  97. is already loaded into another module.  In this case ensure_loaded/1
  98. does nothing; use_module will import all public predicates of the module
  99. into the current context module.
  100. \predicate{use_module}{2}{+File, +ImportList}
  101. Load the file specified with \arg{File} (only one file is accepted).
  102. \arg{File} should be a module file. \arg{ImportList} is a list of
  103. name/arity pairs specifying the predicates that should be imported from
  104. the loaded module.  If a predicate is specified that is not exported from
  105. the loaded module a warning will be printed.  The predicate will
  106. nevertheless be imported to simplify debugging.
  107. \predicate{import}{1}{+Head}
  108. Import predicate \arg{Head} into the current context module. \arg{Head}
  109. should specify the source module using the \mbox{<module>:<term>}
  110. construct. Note that predicates are normally imported using one of the
  111. directives use_module/[1,2]. import/1 is meant for handling imports
  112. into dynamically created modules.
  113. \end{description}
  114. It would be rather inconvenient to have to import each predicate
  115. referred to by the module, including the system predicates.  For this
  116. reason each module is assigned a \jargon{default module}.  All predicates
  117. in the default module are available without extra declarations.  Their
  118. definition however can be overruled in the local module.  This schedule
  119. is implemented by the exception handling mechanism of SWI-Prolog:  if
  120. an undefined predicate exception is raised for a predicate in some
  121. module, the exception handler first tries to import the predicate from
  122. the module's default module.  On success, normal execution is resumed.
  123. \subsection{Reserved Modules}
  124. SWI-Prolog contains two special modules.  The first one is the module
  125. \const{system}.  This module contains all built-in predicates described
  126. in this manual.  Module \const{system} has no default module assigned to
  127. it.  The second special module is the module \const{user}.  This module
  128. forms the initial working space of the user.  Initially it is empty.
  129. The default module of module \const{user} is \const{system}, making all
  130. built-in predicate definitions available as defaults.  Built-in
  131. predicates thus can be overruled by defining them in module \const{user}
  132. before they are used.
  133. All other modules default to module \const{user}.  This implies they can
  134. use all predicates imported into \const{user} without explicitly
  135. importing them.
  136. \section{Using the Module System}
  137. The current structure of the module system has been designed with some
  138. specific organisations for large programs in mind.  Many large
  139. programs define a basic library layer on top of which the actual
  140. program itself is defined.  The module \const{user}, acting as the
  141. default module for all other modules of the program can be used to
  142. distribute these definitions over all program module without
  143. introducing the need to import this common layer each time
  144. explicitly.  It can also be used to redefine built-in predicates
  145. if this is required to maintain compatibility to some other Prolog
  146. implementation.  Typically, the loadfile of a large application
  147. looks like this:
  148. \begin{code}
  149. :- use_module(compatibility).   % load XYZ prolog compatibility
  150. :- use_module(                  % load generic parts
  151.         [ error                 % errors and warnings
  152.         , goodies               % general goodies (library extensions)
  153.         , debug                 % application specific debugging
  154.         , virtual_machine       % virtual machine of application
  155.         , ...                   % more generic stuff
  156.         ]).
  157. :- ensure_loaded(
  158.         [ ...                   % the application itself
  159.         ]).
  160. \end{code}
  161. The `use_module' declarations will import the public predicates from
  162. the generic modules into the \const{user} module.  The `ensure_loaded'
  163. directive loads the modules that constitute the actual application.
  164. It is assumed these modules import predicates from each other using
  165. use_module/[1,2] as far as necessary.
  166. In combination with the object-oriented schema described below it is
  167. possible to define a neat modular architecture.  The generic code
  168. defines general utilities and the message passing predicates ({invoke}/3
  169. in the example below).  The application modules define classes that
  170. communicate using the message passing predicates.
  171. \subsection{Object Oriented Programming}
  172. Another typical way to use the module system is for defining classes
  173. within an object oriented paradigm.  The class structure and the
  174. methods of a class can be defined in a module and the explicit
  175. module-boundary  overruling describes in \secref{overrule}
  176. can by used by the message passing code to invoke the behaviour.  An
  177. outline of this mechanism is given below.
  178. \begin{code}
  179. %       Define class point
  180. :- module(point, []).           % class point, no exports
  181. %        name           type,           default access
  182. %                                       value
  183. variable(x,             integer,        0,      both).
  184. variable(y,             integer,        0,      both).
  185. %         method name   predicate name  arguments
  186. behaviour(mirror,       mirror,         []).
  187. mirror(P) :-
  188.         fetch(P, x, X),
  189.         fetch(P, y, Y),
  190.         store(P, y, X),
  191.         store(P, x, Y).
  192. \end{code}
  193. The predicates {fetch}/3 and {store}/3 are predicates that change
  194. instance variables of instances. The figure below indicates how message
  195. passing can easily be implemented:
  196. \begin{code}
  197. %       invoke(+Instance, +Selector, ?ArgumentList)
  198. %       send a message to an instance
  199. invoke(I, S, Args) :-
  200.         class_of_instance(I, Class),
  201.         Class:behaviour(S, P, ArgCheck), !,
  202.         convert_arguments(ArgCheck, Args, ConvArgs),
  203.         Goal =.. [P|ConvArgs],
  204.         Class:Goal.
  205. \end{code}
  206. The construct <Module>:<Goal> explicitly calls \arg{Goal} in
  207. module \arg{Module}.  It is discussed in more detail in
  208. \secref{metacall}.
  209. \section{Meta-Predicates in Modules}
  210. As indicated in the introduction, the problem with a predicate based
  211. module system lies in the difficulty to find the correct predicate
  212. from a Prolog term.  The predicate `solution(Solution)' can exist in
  213. more than one module, but `assert(solution(4))' in some module is
  214. supposed to refer to the correct version of {solution}/1.
  215. Various approaches are possible to solve this problem.  One is to add
  216. an extra argument to all predicates (e.g.\ `assert(Module, Term)').
  217. Another is to tag the term somehow to indicate which module is desired
  218. (e.g.\ `assert(Module:Term)').  Both approaches are not very
  219. attractive as they make the user responsible for choosing the correct
  220. module, inviting unclear programming by asserting in other modules.
  221. The predicate assert/1 is supposed to assert in the module it is
  222. called from and should do so without being told explicitly.  For
  223. this reason, the notion \jargon{context module} has been introduced.
  224. \subsection{Definition and Context Module}
  225. Each predicate of the program is assigned a module, called it's
  226. \jargon{definition module}. The definition module of a predicate is
  227. always the module in which the predicate was originally defined. Each
  228. active goal in the Prolog system has a \jargon{context module} assigned
  229. to it.
  230. The context module is used to find predicates from a Prolog term. By
  231. default, this module is the definition module of the predicate running
  232. the goal. For meta-predicates however, this is the context module of the
  233. goal that invoked them. We call this \jargon{module_transparent} in
  234. SWI-Prolog. In the `using maplist' example above, the predicate
  235. maplist/3 is declared module_transparent. This implies the context
  236. module remains \const{extend}, the context module of {add_extension}/3.
  237. This way maplist/3 can decide to call extend_atom in module
  238. \const{extend} rather than in it's own definition module.
  239. All built-in predicates that refer to predicates via a Prolog term are
  240. declared module_transparent.  Below is the code defining maplist.
  241. \begin{code}
  242. :- module(maplist, maplist/3).
  243. :- module_transparent maplist/3.
  244. %       maplist(+Goal, +List1, ?List2)
  245. %       True if Goal can successfully be applied to all successive pairs
  246. %       of elements of List1 and List2.
  247. maplist(_, [], []).
  248. maplist(Goal, [Elem1|Tail1], [Elem2|Tail2]) :-
  249.         apply(Goal, [Elem1, Elem2]), 
  250.         maplist(Goal, Tail1, Tail2).
  251. \end{code}
  252. \subsection{Overruling Module Boundaries}       \label{sec:overrule}
  253. The mechanism above is sufficient to create an acceptable module
  254. system.  There are however cases in which we would like to be able to
  255. overrule this schema and explicitly call a predicate in some module
  256. or assert explicitly in some module.  The first is useful to invoke
  257. goals in some module from the user's toplevel or to implement a
  258. object-oriented system (see above).  The latter is useful to create
  259. and modify \jargon{dynamic modules} (see \secref{dynamic-modules}). 
  260. For this purpose, the reserved term \functor{:}{2} has been introduced.
  261. All built-in predicates that transform a term into a predicate
  262. reference will check whether this term is of the form
  263. \mbox{`<Module>:<Term>'}.  If so, the predicate is searched
  264. for in \arg{Module} instead of the goal's context module.  The
  265. \op{:} operator may be nested, in which case the inner-most module
  266. is used.
  267. The special calling construct \mbox{<Module>:<Goal>} pretends
  268. \arg{Goal} is called from \arg{Module} instead of the context module.
  269. Examples:
  270. \begin{code}
  271. ?- assert(world:done).  % asserts done/0 into module world
  272. ?- world:assert(done).  % the same
  273. ?- world:done.          % calls done/0 in module world
  274. \end{code}
  275. \section{Dynamic Modules}               \label{sec:dynamic-modules}
  276. So far, we discussed modules that were created by loading a
  277. module-file.  These modules have been introduced on facilitate the
  278. development of large applications.  The modules are fully defined at
  279. load-time of the application and normally will not change during 
  280. execution.  Having the notion of a set of predicates as a
  281. self-contained world can be attractive for other purposes as well.
  282. For example, assume an application that can reason about multiple
  283. worlds.  It is attractive to store the data of a particular world in a
  284. module, so we extract information from a world simply by invoking
  285. goals in this world.
  286. Dynamic modules can easily be created.  Any built-in predicate that
  287. tries to locate a predicate in a specific module will create this
  288. module as a side-effect if it did not yet exist.  Example:
  289. \begin{code}
  290. ?- assert(world_a:consistent),
  291.    world_a:unknown(_, fail).
  292. \end{code}
  293. These calls create a module called `world_a' and make the call
  294. `world_a:consistent' succeed.  Undefined predicates will not start the
  295. tracer or autoloader for this module (see unknown/2).
  296. Import and export from dynamically created world is arranged via the
  297. predicates import/1 and export/1:
  298. \begin{code}
  299. ?- world_b:export(solve(_,_)).          % exports solve/2 from world_b
  300. ?- world_c:import(world_b:solve(_,_)).  % and import it to world_c
  301. \end{code}
  302. \section{Module Handling Predicates}
  303. This section gives the predicate definitions for the remaining
  304. built-in predicates that handle modules.
  305. \begin{description}
  306.     \directive{module}{2}{+Module, +PublicList}
  307. This directive can only be used as the first term of a source file. It
  308. declares the file to be a \jargon{module file}, defining \arg{Module} and
  309. exporting the predicates of \arg{PublicList}. \arg{PublicList} is a
  310. list of name/arity pairs.
  311.     \prefixop{module_transparent}{+Preds}
  312. \arg{Preds} is a comma separated list of name/arity pairs (like
  313. dynamic/1).  Each goal associated with a transparent declared predicate
  314. will inherit the \jargon{context module} from its parent goal.
  315.     \prefixop{meta_predicate}{+Heads}
  316. This predicate is defined in \pllib{quintus} and provides a partial
  317. emulation of the Quintus predicate.  See \secref{metapredicate} for
  318. details.
  319.     \predicate{current_module}{1}{-Module}
  320. Generates all currently known modules.
  321.     \predicate{current_module}{2}{?Module, ?File}
  322. Is true if \arg{File} is the file from which \arg{Module} was loaded.
  323. \arg{File} is the internal canonical filename. See also
  324. source_file/[1,2].
  325.     \predicate{context_module}{1}{-Module}
  326. Unify \arg{Module} with the context module of the current goal.
  327. context_module/1 itself is transparent.
  328.     \predicate{export}{1}{+Head}
  329. Add a predicate to the public list of the context module.  This implies
  330. the predicate will be imported into another module if this module is
  331. imported with use_module/[1,2].  Note that predicates are normally
  332. exported using the directive module/2. export/1 is meant to handle
  333. export from dynamically created modules.
  334.     \predicate{export_list}{2}{+Module, ?Exports}
  335. Unifies \arg{Exports} with a list of terms.  Each term has the name and
  336. arity of a public predicate of \arg{Module}.  The order of the terms in
  337. \arg{Exports} is not defined.  See also predicate_property/2.
  338.     \predicate{default_module}{2}{+Module, -Default}
  339. Succesively unifies \arg{Default} with the module names from which
  340. a call in \arg{Module} attempts to use the definition.  For the
  341. module \const{user}, this will generate \const{user} and \const{system}.
  342. For any other module, this will generate the module itself, followed
  343. by \const{user} and \const{system}.
  344.     \predicate{module}{1}{+Module}
  345. The call \exam{module(\arg{Module})} may be used to switch the default
  346. working module for the interactive toplevel (see prolog/0).  This may
  347. be used to when debugging a module. The example below lists the clauses
  348. of {file_of_label}/2 in the module \const{tex}.
  349. \begin{code}
  350. 1 ?- module(tex).
  351. tex: 2 ?- listing(file_of_label/2).
  352. \end{code}
  353. \end{description}
  354. \section{Compatibility of the Module System}
  355. The principles behind the module system of SWI-Prolog differ in a
  356. number of aspects from the Quintus Prolog module system.
  357. \begin{itemize}
  358.     \item
  359. The SWI-Prolog module system allows the user to redefine system
  360. predicates.
  361.     \item
  362. All predicates that are available in the \const{system} and \const{user}
  363. modules are visible in all other modules as well.
  364.     \item
  365. Quintus has the `meta_predicate/1' declaration were SWI-Prolog has the
  366. module_transparent/1 declaration.
  367. \end{itemize}
  368. The meta_predicate/1 declaration causes the compiler to tag arguments
  369. that pass module sensitive information with the module using the
  370. \functor{:}{2} operator.  This approach has some disadvantages:
  371. \begin{itemize}
  372.     \item
  373. Changing a meta_predicate declaration implies all predicates
  374. \strong{calling} the predicate need to be reloaded. This can cause
  375. serious consistency problems.
  376.     \item
  377. It does not help for dynamically defined predicates calling module
  378. sensitive predicates.
  379.     \item
  380. It slows down the compiler (at least in the SWI-Prolog architecture).
  381.     \item
  382. At least within the SWI-Prolog architecture the run-time overhead is
  383. larger than the overhead introduced by the transparent mechanism.
  384. \end{itemize}
  385. Unfortunately the transparent predicate approach also has some
  386. disadvantages. If a predicate $A$ passes module sensitive information
  387. to a predicate $B$, passing the same information to a module
  388. sensitive system predicate both $A$ and $B$ should be declared
  389. transparent. Using the Quintus approach only $A$ needs to be
  390. treated special (i.e. declared with meta_predicate/1)%
  391.     \footnote{Although this would make it impossible to call $B$
  392.               directly.}.
  393. A second problem arises if the body of a transparent predicate uses
  394. module sensitive predicates for which it wants to refer to its own
  395. module. Suppose we want to define findall/3 using assert/1 and
  396. retract/1%
  397.     \footnote{The system version uses recordz/2 and recorded/3.}.
  398. The example in \figref{findall} gives the solution.
  399. \begin{figure}
  400. \begin{code}
  401. :- module(findall, [findall/3]).
  402. :- dynamic
  403.         solution/1.
  404. :- module_transparent
  405.         findall/3, 
  406.         store/2.
  407. findall(Var, Goal, Bag) :-
  408.         assert(findall:solution('$mark')), 
  409.         store(Var, Goal), 
  410.         collect(Bag).
  411. store(Var, Goal) :-
  412.         Goal,                   % refers to context module of
  413.                                 % caller of findall/3
  414.         assert(findall:solution(Var)), 
  415.         fail.
  416. store(_, _).
  417. collect(Bag) :-
  418.         ..., 
  419. \end{code}
  420.     \caption{findall/3 using modules}
  421.     \label{fig:findall}
  422. \end{figure}
  423. \subsection{Emulating meta_predicate/1}        \label{sec:metapredicate}
  424. The Quintus meta_predicate/1 directive can in many cases be replaced by
  425. the transparent declaration. Below is the definition of meta_predicate/1
  426. as available from \pllib{quintus}.
  427. \begin{code}
  428. :- op(1150, fx, (meta_predicate)).
  429. meta_predicate((Head, More)) :- !, 
  430.         meta_predicate1(Head), 
  431.         meta_predicate(More).
  432. meta_predicate(Head) :-
  433.         meta_predicate1(Head).
  434. meta_predicate1(Head) :-
  435.         Head =.. [Name|Arguments], 
  436.         member(Arg, Arguments), 
  437.         module_expansion_argument(Arg), !, 
  438.         functor(Head, Name, Arity), 
  439.         module_transparent(Name/Arity).
  440. meta_predicate1(_).             % just a mode declaration
  441. module_expansion_argument(:).
  442. module_expansion_argument(N) :- integer(N).
  443. \end{code}
  444. The discussion above about the problems with the transparent mechanism
  445. show the two cases in which this simple transformation does not work.
  446.